package com.eet.rabbitmq.work.fair;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 消费者
 *
 * @author zheng.zhang
 */
@SuppressWarnings("all")
public class Consumer1 implements Runnable {
    private static final Runnable RUNNABLE = new Consumer1();

    @Override
    public void run() {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("www.eet.ink");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        try (final Connection connection = factory.newConnection();
             final Channel channel = connection.createChannel()) {
            String queueName = Thread.currentThread().getName();
            // 每次从队列读取一条消息
            channel.basicQos(1);
            channel.basicConsume(queueName, false,
                    (consumerTag, message) -> {
                        System.out.println(queueName + "收到的消息为: " + new String(message.getBody(), StandardCharsets.UTF_8));
                        try {
                            TimeUnit.MICROSECONDS.sleep(600);
                            // 手动确认
                            channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    },
                    consumerTag -> System.out.println("消息接收失败!!!"));
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Thread(RUNNABLE, "work.queue.polling").start();
    }
}
